package com.wjerp.tplus.server.common.utils;

import com.wjerp.tplus.server.common.constant.RedisKey;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 编码生成器
 * @author lishuailei
 */
@Component
public class CodeGeneratorUtils {

    /**
     * 编码生成集合标记
     */
    private static final String CODE_GENERATE_KEY_PRE = "CODE_MAP_";

    /**
     * 公司编码前缀
     */
    private static final String PRE_COMPANY_CODE = "C";


    /**
     * 系统用户编码前缀
     */
    private static final String PRE_SYS_USER_CODE = "S";

    /**
     * 公司账户编码前缀
     */
    private static final String PRE_COMPANY_ACCOUNT_CODE = "A";

    /**
     * 发票编码前缀
     */
    private static final String PRE_INVOICE_CODE = "I";

    @Resource
    private RedisUtils redisUtils;

    public String formatDate(){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate localDate= LocalDate.now();
        String strDate=localDate.format(dtf);
        return strDate;
    }

    /**
     * 生成发票唯一码
     * @return
     */
    public String generateInvoiceUuidCode(){
        String code = generateCode(PRE_INVOICE_CODE, RedisKey.INVOICE_CODE);
        return code;
    }


    /**
     * 生成企业账户编码
     * @return
     */
    public String generateCompanyAccountCode(){
        String code = generateCode(PRE_COMPANY_ACCOUNT_CODE, RedisKey.COMPANY_ACCOUNT_CODE);
        return code;
    }

    /**
     * 生成系统用户编码
     * @return
     */
    public String generateSysUserCode(){
        String code = generateCode(PRE_SYS_USER_CODE, RedisKey.SYS_USER_CODE);
        return code;
    }

    /**
     * 生成企业编码
     * @return
     */
    public String generateCompanyCode(){
        String code = generateCode(PRE_COMPANY_CODE, RedisKey.COMPANY_CODE);
        return code;
    }

    /**
     * 生成编码
     * @param preCode 前缀码
     * @param redisKey 缓存KEY
     * @return
     */
    private String generateCode(String preCode,String redisKey){
        Long num = redisUtils.incrementByDay(CODE_GENERATE_KEY_PRE + formatDate() + redisKey);
        return preCode + formatDate()+""+String.format("%06d", num);
    }
}
